package com.gzist.blog_system.filter;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.gzist.blog_system.config.expection.CustomerAuthenticationException;
import com.gzist.blog_system.handler.LoginFailureHandler;
import com.gzist.blog_system.util.JWTUtils;
import com.gzist.blog_system.web.SysUserDetailsService;
import io.jsonwebtoken.Claims;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 * @description:
 *  认证过滤器（处理token进行状态校验）
 * @author: 黄泽建
 **/

/**
 * token验证过滤器
 */
@Data
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private SysUserDetailsService customerUserDetailsService;
    @Resource
    private LoginFailureHandler loginFailureHandler;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //获取登录请求地址
    @Value("${request.login.url}")
    private String loginUrl;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain) throws ServletException,
            IOException {
        try {
            //获取当前请求的url地址
            String url = request.getRequestURI();
            log.info("打印当前的请求路径{}", url);
            //放行接口文档资源的访问
            if (url.contains("html")||url.contains("webjars")||
                    url.contains("swagger-resources")||url.contains("v2/api-docs")) {
                doFilter(request, response, filterChain);
                return;
            }
            //如果是对于文章数据的请求均放行给首页(除了加改)
            if (url.contains("article") || url.contains("statistic")) {
                if (!(url.contains("add") || url.contains("update"))) {
                    doFilter(request, response, filterChain);
                    return;
                }
            }
            // 当请求身份密钥的时候给其放行
            if (url.equals("/user/key")) {
                doFilter(request, response, filterChain);
                return;
            }
            // 当请求注册的时候给其放行
            if (url.equals("/user/register")) {
                doFilter(request, response, filterChain);
                return;
            }
            //如果当前请求不是登录请求，则需要进行token验证
            if (!url.contains(loginUrl)) {
                this.validateToken(request);
            }

        } catch (AuthenticationException e) {
            loginFailureHandler.onAuthenticationFailure(request, response, e);
        }
        //登录请求不需要验证token
        doFilter(request, response, filterChain);
    }

    /**
     * 验证token
     *
     * @param request
     */
    private void validateToken(HttpServletRequest request) throws AuthenticationException {
        //从头部获取token信息
        String token = request.getHeader("Authorization");
        log.info("token3333===>{}", token);
        //如果请求头部没有获取到token，则从请求的参数中进行获取
        if (ObjectUtils.isEmpty(token)) {
            log.info("token为空吗？11===>{}", token);
            token = request.getParameter("Authorization");
        }
        //如果请求参数中也不存在token信息，则抛出异常
        if (ObjectUtils.isEmpty(token)) {
            log.info("token为空吗？22===>{}", token);
            throw new CustomerAuthenticationException("token不存在");
        }
        //判断redis中是否存在该token
        String redisToken = stringRedisTemplate.opsForValue().get(token);
        //如果redis里面没有token,说明该token失效
        if (ObjectUtils.isEmpty(redisToken)) {
            log.info("token为空吗？===>{}", token);
            throw new CustomerAuthenticationException("token已过期");
        }
        //先从token中拿到用户名
        String username = "";
        try {
            Claims claims = JWTUtils.parseJwt(token);
            username = (String) claims.get("username");
        } catch (Exception e) {
            throw new CustomerAuthenticationException("token验证失败");
        }
        //拿到用户名然后再从上下文拿到用户信息
        UserDetails userDetails =
                customerUserDetailsService.loadUserByUsername(username);
        //判断用户信息是否为空
        if (userDetails == null) {
            throw new CustomerAuthenticationException("token验证失败");
        }
        //创建身份验证对象
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails, null,
                userDetails.getAuthorities());
        authenticationToken.setDetails(new
                WebAuthenticationDetailsSource().buildDetails(request));
        //设置到Spring Security上下文
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }
}